# encoding: utf-8
from flask import Blueprint,request,make_response,g
from utils import restful,czcache
from utils.captcha import Captcha
from exts import alidayu
from apps.common.forms import SMSCaptchaForm
from io import BytesIO



bp = Blueprint('common',__name__,url_prefix='/c')

# 手机验证码
# @bp.route('/sms_captcha/')
# def sms_captcha():
#     #  获取前端手机号码
#     telephone = request.args.get('telephone')
#     # 判断是否有手机号码
#     if not telephone:
#         return restful.params_error(message='请输入手机号码')
#     captcha = Captcha.gene_text(number=4)
#     result = alidayu.send_sms(telephone, code=captcha)
#     if result:
#         return restful.success()
#     else:
#         return restful.params_error(message='服务器忙，请稍后再试')

@bp.route('/sms_captcha/',methods=['POST'])
def sms_captcha():
    form = SMSCaptchaForm(request.form)
    if form.validate():
        telephone = form.telephone.data
        captcha = Captcha.gene_text(number=4)
        if alidayu.send_sms(telephone,code=captcha):
            czcache.set(telephone,captcha.lower())
            return restful.success()
        else:
            return restful.params_error(message='参数错误！')
    else:
        return restful.params_error(message=form.get_error())


@bp.route('/captcha/')
def graph_captcha():
    # 获取验证码
    text,image = Captcha.gene_graph_captcha()
    czcache.set(text.lower(),text.lower())
    out = BytesIO()
    image.save(out,'png')
    out.seek(0)
    resp = make_response(out.read())
    resp.content_type = 'image/png'
    return resp
